<template>
  <div class="work-container">
    <van-panel :title="rworkId?'修改计件报工单':'添加计件报工'">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        :disabled="!rworkUser"
        label-width="80px"
      >
        <el-form-item
          label="鼓号/批号"
          prop="wtermDnumber"
        >
          <el-input
            v-model="form.wtermDnumber"
            placeholder="请输入生产鼓号"
          />
        </el-form-item>

        <el-form-item
          label="订单编号"
          prop="wtermOnumber"
        >
          <el-autocomplete
            class="inline-input"
            v-model="form.wtermOnumber"
            :fetch-suggestions="querySearchOrder"
            placeholder="请输入订单编号"
            :trigger-on-focus="false"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item
          label="所属模块"
          prop="moduleId"
        >
          <el-select
            v-model="form.moduleId"
            :disabled="true"
            filterable
            @change="handleChangeModule"
            placeholder="请选择所属模块"
          >
            <el-option
              v-for="item in moduleOptions"
              :key="item.moduleId"
              :label="item.moduleName"
              :value="item.moduleId"
              :disabled="item.status == 1"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="所属车间"
          prop="workshopId"
        >
          <el-select
            v-model="form.workshopId"
            filterable
            @change="handleChangeWorkshop"
            placeholder="请选择所属车间"
          >
            <el-option
              v-for="item in workshopOptions"
              :key="item.workshopId"
              :label="item.workshopName"
              :value="item.workshopId"
              :disabled="item.status == 1"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="大工序"
          prop="gprocessId"
        >
          <el-select
            v-model="form.gprocessId"
            filterable
            @change="handleChangeProcess"
            placeholder="请选择大工序"
          >
            <el-option
              v-for="item in gprocessOptions"
              :key="item.gprocessId"
              :label="item.gprocessName"
              :value="item.gprocessId"
              :disabled="item.status == 1"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="小工序ID"
          prop="processId"
        >
          <el-select
            v-model="form.processId"
            filterable
            @change="handleGetProcessPay"
            placeholder="请选择小工序"
          >
            <el-option
              v-for="item in processOptions"
              :key="item.processId"
              :label="item.processName"
              :value="item.processId"
              :disabled="item.status == 1"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="工序单价"
          prop="processPay"
        >
          <el-input
            v-model="form.processPay"
            :disabled="true"
            placeholder="选择小工序后自动获取"
          />
        </el-form-item>
        <el-form-item
          label="品种"
          prop="breedId"
        >
          <!-- <el-input v-model="form.breedName" style="width:100%" placeholder="请输入品种"></el-input> -->
          <el-autocomplete
            v-model="form.breedName"
            :fetch-suggestions="querySearchBreed"
            placeholder="请输入品种"
            :trigger-on-focus="false"
          ></el-autocomplete>
        </el-form-item>

        <el-form-item
          label="颜色"
          prop="colourId"
        >
          <!-- <el-input v-model="form.colourName" style="width:100%" placeholder="请输入颜色"></el-input> -->
          <el-autocomplete
            v-model="form.colourName"
            :fetch-suggestions="querySearchColour"
            placeholder="请输入颜色"
            :trigger-on-focus="false"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item
          label="工艺要求"
          prop="rworkTr"
        >
          <el-input
            v-model="form.rworkTr"
            placeholder="请输入工艺要求"
          />
        </el-form-item>
        <el-form-item
          label="单位"
          prop="rworkDw"
        >
          <el-input
            v-model="form.rworkDw"
            placeholder="请输入单位"
          />
        </el-form-item>
        <el-form-item
          label="计划生产"
          prop="rworkPlan"
        >
          <el-input
            v-model="form.rworkPlan"
            class="def-input-number"
            type="number"
            placeholder="请输入计划生产"
          />
        </el-form-item>
        <el-form-item
          label="实际生产"
          prop="rworkActual"
        >
          <el-input
            v-model="form.rworkActual"
            @change="handleCountPay"
            class="def-input-number"
            type="number"
            placeholder="请输入实际生产"
          />
        </el-form-item>
        <el-form-item
          label="重复次数"
          prop="rworkRepetitions"
        >
          <el-input-number
            v-model="form.rworkRepetitions"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
        <el-form-item
          label="开始时间"
          prop="rworkStart"
        >
          <div class="flex-box">
            <el-date-picker
              clearable
              style="width:100%"
              v-model="form.rworkStart"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              default-time="12:00:00"
              placeholder="请选择开始时间"
              :picker-options="pickerOptions"
              @change="handleCompareTime"
            >
            </el-date-picker>
            <el-button
              type="text"
              @click="setTime(1)"
            >此刻</el-button>
          </div>
        </el-form-item>
        <el-form-item
          label="结束时间"
          prop="rworkEnd"
        >
          <div class="flex-box">
            <el-date-picker
              clearable
              style="width:100%"
              v-model="form.rworkEnd"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              default-time="12:00:00"
              placeholder="请选择结束时间"
              :picker-options="pickerOptions"
              @change="handleCompareTime"
            >
            </el-date-picker>
            <el-button
              type="text"
              @click="setTime(2)"
            >此刻</el-button>
          </div>
        </el-form-item>
        <el-form-item
          label="工作时长"
          prop="rworkDuration"
        >
          <el-input
            v-model="form.rworkDuration"
            class="def-input-number"
            type="number"
            placeholder="请输入工作时长"
          />
        </el-form-item>
        <el-form-item
          label="预估工资"
          prop="estimatePay"
        >
          <el-input
            v-model="form.estimatePay"
            disabled
            placeholder="请输入预估工资"
          />
        </el-form-item>
      </el-form>
    </van-panel>
    <van-panel title="操作人">
      <div class="control-btns">
        <van-button
          :disabled="!rworkUser"
          size="small"
          type="primary"
          icon="plus"
          @click="addPeople"
        >添加操作人</van-button>
        <van-button
          :disabled="!rworkUser"
          size="small"
          type="info"
          icon="friends-o"
          @click="loadPeople"
        >上一次操作人</van-button>
        <van-button
          :disabled="!rworkUser"
          size="small"
          type="danger"
          icon="delete-o"
          @click="clearPeople"
        >清空操作人</van-button>
      </div>
      <div
        v-for="(item, index) in slRworkRmemberList"
        :key="index"
        class="user-panel"
      >
        <van-icon
          class="close-btn"
          name="close"
          size="20"
          color="#ff4949"
          @click="handleDeleteSlRworkRmember(index)"
        />
        <van-cell-group>
          <van-field
            label-width="4em"
            label="参与人"
            :value="item.rmemberNick"
            readonly
          />
          <van-field
            label-width="4em"
            name="radio"
            label="班组"
          >
            <template #input>
              <van-radio-group
                v-model="item.rmemberBz"
                direction="horizontal"
              >
                <van-radio
                  v-for="dict in dict.type.sl_rwork_class"
                  :key="dict.value"
                  :name="dict.value"
                >{{dict.label}}</van-radio>
              </van-radio-group>
              <van-icon
                class="cancel-btn"
                name="close"
                @click="cancelBz(item)"
              />
            </template>
          </van-field>
          <van-field
            v-if="item.ssmId=='5'||item.levelId==6||item.levelId==7||item.levelId==8"
            label-width="4em"
            v-model="item.rmemberDuration"
            label="时长"
            placeholder="请输入时长"
          />
        </van-cell-group>
      </div>
      <van-empty
        v-if="!slRworkRmemberList.length"
        image-size="120px"
        description="请选择操作人"
      />
    </van-panel>
    <div class="fixed-bar">
      <van-button
        type="default"
        round
        @click="goback"
      >返回</van-button>
      <van-button
        :disabled="!rworkUser"
        type="info"
        round
        @click="submitForm"
      >保存</van-button>
    </div>

    <van-popup
      v-model="showFlag"
      round
      position="bottom"
      @closed="popupClosed"
    >
      <van-nav-bar
        title="请选择操作人"
        left-text="取消"
        right-text="确认"
        @click-left="onClickLeft"
        @click-right="onClickRight"
      />
      <van-search
        v-model="userQueryParams.nickName"
        placeholder="请输入姓名"
        @search="onSearch"
        @clear="onClear"
      />
      <div style="height: 80vh; overflow: auto;">
        <van-checkbox-group
          v-model="result"
          ref="checkboxGroup"
        >
          <van-cell-group>
            <van-cell
              v-for="(item, index) in userList"
              clickable
              :key="item.userId"
              :title="`${item.userName} - ${item.nickName}`"
              @click="toggle(index)"
            >
              <template #default>
                <span class="dept">{{item.dept?item.dept.deptName:''}}</span>
              </template>
              <template #right-icon>
                <van-checkbox
                  :name="item"
                  ref="checkboxes"
                />
              </template>
            </van-cell>
          </van-cell-group>
        </van-checkbox-group>
      </div>
      <!-- <van-cascader v-model="deptValue" title="请选择部门" :options="deptOptions" @close="showFlag = false" @finish="onFinish" /> -->
    </van-popup>
  </div>
</template>

<script>
import { Notify } from 'vant';
import { Dialog } from 'vant';
import { getRwork, addRwork, updateRwork, rworkUserBase, getRworkOptions, isUniqueUser, getLastmember, getOftenMember } from "@/api/sl/rwork";
import { getProcessListByGprocessId } from "@/api/sl/process";
import { getWorkshopListByModuleId } from "@/api/sl/workshop";
import { getGprocessListByWorkshopId } from "@/api/sl/gprocess";
import { listUserSel } from "@/api/system/user";

export default {
  name: "h5RworkEditSingle",
  components: {
    [Notify.Component.name]: Notify.Component,
    [Dialog.Component.name]: Dialog.Component,
  },
  dicts: ['sl_rwork_class'],
  data() {
    let watermarkContentVaild = (rule, value, callback) => {
      if (value == null || value === "") {
        callback();
      } else {
        let length = value.length
        if (length > 7) {
          callback(new Error("输入不能超过7位"))
        } else {
          callback();
        }
      }
    }
    return {
      rworkId: undefined,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // wtermDnumber: [
        //   { required: true, message: "生产鼓号不能为空", trigger: "blur" }
        // ],
        // wtermOnumber: [{
        //   required: true,
        //   message: "订单编号/生产批号不能为空",
        //   trigger: "blur"
        // }],
        moduleId: [{
          required: true,
          message: "模块不能为空",
          trigger: ["blur", "change"]
        }],
        workshopId: [{
          required: true,
          message: "车间不能为空",
          trigger: ["blur", "change"]
        }],
        gprocessId: [{
          required: true,
          message: "大工序ID不能为空",
          trigger: ["blur", "change"]
        }],
        processId: [{
          required: true,
          message: "小工序ID不能为空",
          trigger: ["blur", "change"]
        }],
        processPay: [
          { required: true, message: "工序单价不能为空", trigger: ["blur", "change"] }
        ],
        rworkPlan: [
          { validator: watermarkContentVaild, trigger: 'blur' }
        ],
        rworkActual: [
          { validator: watermarkContentVaild, trigger: 'blur' }
        ],
        rworkDuration: [
          { validator: watermarkContentVaild, trigger: 'blur' }
        ],
        estimatePay: [
          { validator: watermarkContentVaild, trigger: 'blur' }
        ],
      },
      rworkUser: null,
      //早晚班
      //模块
      moduleOptions: [],
      //车间
      workshopOptions: [],
      //大工序
      gprocessOptions: [],
      //小工序
      processOptions: [],
      // 操作人表格数据
      slRworkRmemberList: [],
      //限制时间选择范围
      pickerOptions: {
        disabledDate(date) {
          let ts = date.getTime()
          let now = Date.now()
          let limitDays = 2 * 24 * 60 * 60 * 1000 // 2天的毫秒数
          if (ts <= now && ts >= now - limitDays) {
            return false;
          } else {
            return true;
          }
        }
      },
      //所有参与人
      attendanceList: [],
      //订单编号
      orderNumList: [],
      //颜色
      colourList: [],
      //品类
      breedList: [],
      userQueryParams: {
        pageNum: 1,
        pageSize: 1000,
        nickName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      },
      userList: [],
      showFlag: false,
      searchValue: '',
      result: [],
    }
  },
  computed: {
  },
  created() {
    //获取当前报工人信息
    this.getRworkUserBase(this.$store.state.user.name);
    this.getUserList();
  },
  watch: {
    "form.processPay":{
      handler(newName, oldName) {
        this.handleCountPay()
      },
    },
    "form.rworkActual":{
      handler(newName, oldName) {
        this.handleCountPay()
      },
    },
    "form.rworkRepetitions":{
      handler(newName, oldName) {
        this.handleCountPay()
      },
    },
  },
  methods: {
    init() {
      this.rworkId = this.$route.query.rworkId;
      console.log(this.rworkId);
      this.reset();
      this.form.moduleId = this.rworkUser.moduleId;
      this.form.workshopId = this.rworkUser.workshopId;
      if (this.rworkId) {
        getRwork(this.rworkId).then(response => {
          this.form = response.data;
          this.gprocessOptions = response.gprocesss;
          this.processOptions = response.processs;
          this.moduleOptions = response.modules;
          this.workshopOptions = response.workshops;
          this.slRworkRmemberList = response.data.slRworkRmemberList;
        });
      }
      const query = {
        moduleId: this.rworkUser.moduleId,
        workshopId: this.rworkUser.workshopId,
        leaderUser: this.rworkUser.leaderUser
      }
      getRworkOptions(query).then(response => {
        this.moduleOptions = response.modules
        this.workshopOptions = response.workshops
        this.gprocessOptions = response.gprocesss
      });
    },
    //获取报工人模块车间信息
    getRworkUserBase(userName) {
      if (userName != null && userName != "") {
        rworkUserBase(userName).then(response => {
          if (response.data != null) {
            this.rworkUser = response.data;
            this.init();
          } else {
            Notify({ type: 'danger', message: '您没有报工权限，请联系管理员。' });
          }
        });
      } else {
        Notify({ type: 'danger', message: '未获取到报工人信息。' });
      }
    },

    // 表单重置
    reset() {
      this.form = {
        rworkId: null,
        rworkDate: null,
        moduleId: null,
        workshopId: null,
        rworkBz: null,
        rworkYear: null,
        rworkMonth: null,
        rworkDay: null,
        isApproved: null,
        createBy: null,
        createTime: null,
        leaderUser: null,
        wtermDnumber: null,
        wtermOnumber: null,
        gprocessId: null,
        processId: null,
        breedName: null,
        colourName: null,
        rworkTr: null,
        rworkDw: null,
        rworkPlan: null,
        rworkActual: null,
        rworkRepetitions: 0,
        rworkStart: null,
        rworkEnd: null,
        rworkDuration: null,
        processPay: null,
        estimatePay: null,
        rworkUser: null,
        rworkDm: null,
        rfworkId: null
      };
      this.slRworkRmemberList = [];
      this.resetForm("form");
    },
    //模块变更查询车间
    handleChangeModule(value) {
      //清空车间
      this.form.workshopId = null;
      this.workshopOptions = [];
      //清空大工序
      this.form.gprocessId = null;
      this.gprocessOptions = [];
      //清空小工序
      this.form.processId = null;
      this.processOptions = [];
      //工序单价
      this.form.processPay = null;
      getWorkshopListByModuleId(value).then(response => {
        this.workshopOptions = response.data;
      });
    },
    //车间变更查询大工序
    handleChangeWorkshop(value) {
      //清空大工序
      this.form.gprocessId = null;
      this.gprocessOptions = [];
      //清空小工序
      this.form.processId = null;
      this.processOptions = [];
      //工序单价
      this.form.processPay = null;
      getGprocessListByWorkshopId(value).then(response => {
        this.gprocessOptions = response.data;
      });
    },
    //大工序变更查询小工序
    handleChangeProcess(value) {
      //清空小工序
      this.form.processId = null;
      this.processOptions = [];
      //工序单价
      this.form.processPay = null;
      getProcessListByGprocessId(value).then(response => {
        this.processOptions = response.data;
      });
    },
    //获取小工序单价
    handleGetProcessPay(value) {
      for (let i = 0; i < this.processOptions.length; i++) {
        if (this.processOptions[i].processId === value) {
          this.form.processPay = this.processOptions[i].processPay;
          break;
        }
      }
      if (this.form.rworkActual) {
        this.handleCountPay();
      }
    },
    //比较时间
    handleCompareTime() {
      if (this.form.rworkStart && this.form.rworkEnd) {
        let difference = new Date(this.form.rworkEnd) - new Date(this.form.rworkStart);
        this.form.rworkDuration = (difference / 3600000).toFixed(2)
      } else {
        this.form.rworkDuration = null;
      }
    },
    querySearchOrder(queryString, cb) {
      var orderNumList = this.orderNumList;
      var results = queryString ? orderNumList.filter(this.createFilter(queryString, "order")) : orderNumList;
      cb(results);
    },
    querySearchBreed(queryString, cb) {
      var breedList = this.breedList;
      var results = queryString ? breedList.filter(this.createFilter(queryString, "breed")) : breedList;
      cb(results);
    },
    querySearchColour(queryString, cb) {
      var colourList = this.colourList;
      var results = queryString ? colourList.filter(this.createFilter(queryString, "colour")) : colourList;
      cb(results);
    },
    createFilter(queryString, type) {
      if (type === "order") {
        return (order) => {
          return (order.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      } else if (type === "colour") {
        return (colour) => {
          return (colour.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      } else if (type === "breed") {
        return (breed) => {
          return (breed.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      }

    },
    handleCountPay() {
      const res = this.form.processPay * this.form.rworkActual * this.form.rworkRepetitions;
      this.form.estimatePay = Number(res.toFixed(3));
    },
    /** 查询用户列表 */
    getUserList() {
      this.loading = true;
      listUserSel(this.userQueryParams).then(response => {
        this.userList = response.rows;
        getOftenMember(this.$store.state.user.name).then(response => {
          const valuesToBringFront = response.data || [];
          if (valuesToBringFront.length) {
            this.userList.sort((a, b) => {
              if (valuesToBringFront.includes(a.userName) && !valuesToBringFront.includes(b.userName)) {
                return -1;
              } else if (!valuesToBringFront.includes(a.userName) && valuesToBringFront.includes(b.userName)) {
                return 1;
              }
              return 0;
            });
          }
        });
        this.loading = false;
      });

    },
    popupClosed() {
      this.$refs.checkboxGroup.toggleAll(false);
    },
    onClickLeft() {
      console.log('取消');
      this.showFlag = false;
    },
    onClickRight() {
      this.showFlag = false;
      console.log(this.result);
      if (this.result && this.result.length) {
        this.userSelected(this.result);
      }
    },
    userSelected(rows) {
      if (rows != null) {
        rows.forEach(user => {
          //console.log(user)
          let obj = {};
          obj.rmemberUser = user.userName;
          obj.rmemberNick = user.nickName;
          obj.levelId = user.levelId;
          obj.ssmId = user.ssmId;
          obj.levelName = user.level?.levelName;
          obj.ssmName = user.ssm?.ssmName;
          obj.isFormalworker = user.isFormalworker;
          obj.isHourlyworker = user.isHourlyworker;
          obj.rmemberBz = "3";
          if (isUniqueUser(this.slRworkRmemberList, obj)) {
            this.slRworkRmemberList.push(obj);
          }
        })
      }
    },
    handleDeleteSlRworkRmember(index) {
      this.slRworkRmemberList.splice(index, 1);
    },
    addPeople() {
      this.showFlag = true;
    },
    loadPeople() {
      this.loading = true;
      getLastmember().then(response => {
        if (response.data && response.data.length) {
          this.slRworkRmemberList = response.data;
        } else {
          Notify({ type: 'warning', message: '没有获取到上次操作人。' });
        }
        this.loading = false;
      });
    },
    clearPeople() {
      this.slRworkRmemberList = [];
    },
    onSearch() {
      this.getUserList();
    },
    onClear() {
      this.userQueryParams.userName = undefined;
      this.getUserList();
    },
    toggle(index) {
      this.$refs.checkboxes[index].toggle();
    },
    goback() {
      this.$router.go(-1);
    },
    cancelBz(item) {
      console.log(item);
      item.rmemberBz = undefined;
    },
    setTime(num) {
      if (num === 1) {
        this.form.rworkStart = this.parseTime(new Date());
      } else if (num === 2) {
        this.form.rworkEnd = this.parseTime(new Date());
      }
      this.handleCompareTime();
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.$refs["form"]);
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.slRworkRmemberList.length == 0) {
            Notify({ type: 'danger', message: '操作人不能为空。' });
            return;
          }

          //直属领导
          this.form.leaderUser = this.rworkUser.leaderUser;

          this.form.slRworkRmemberList = this.slRworkRmemberList;
          if (this.form.rworkId != null) {
            Dialog.confirm({
              title: '提示',
              message: '是否确认重新提交审批？',
            }).then(() => {
              updateRwork(this.form).then(response => {
                Notify({ type: 'success', message: '重新提交成功' });
                this.$router.go(-1);
              });
            }).catch(() => {
              // on cancel
            });
          } else {
            addRwork(this.form).then(response => {
              Notify({ type: 'success', message: '新增成功' });
              this.$router.go(-1);
            });
          }
        }
      });
    },
  }
};
</script>

<style lang="scss" scoped>
.work-container {
  padding-bottom: 80px;
  &::v-deep {
    .van-cell-group {
      & + .van-cell-group {
        margin-top: 10px;
      }
    }
    .van-panel__header {
      font-size: 16px;
      font-weight: bold;
      span {
        &::before {
          content: '□';
          margin-right: 6px;
        }
      }
    }
    .van-panel__content {
      padding: 15px;
    }
    .el-select,
    .el-autocomplete {
      display: block;
    }
    .el-input-number {
      width: 100%;
    }
    .van-radio-group--horizontal {
      flex: 1;
    }
  }
}
.flex-box {
  display: flex;
  &::v-deep {
    .el-input {
      flex: 1;
    }
    .el-button {
      margin-left: 5px;
    }
  }
}
.cancel-btn {
  // font-size: 12px;
}
.fixed-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background-color: #fff;
  padding: 10px 15px;
  text-align: right;
  display: flex;
  justify-content: space-between;
  box-shadow: 0 0 10px 5px rgba(51, 51, 51, 0.04);
  button {
    width: 48%;
  }
}
.dept {
  margin-right: 10px;
  font-size: 12px;
}
.user-panel {
  position: relative;
  padding: 5px;
  background-color: #ebedf0;
  margin-top: 5px;
  .close-btn {
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 1;
  }
}
.control-btns {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
@media (max-width: 550px) {
}
</style>
